#include <iostream>
#include <iterator>
#include <vector>
#include <list>
#include <algorithm>
#include <fstream>
#include <string>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "CShellProcess.h"

using namespace std;

class CPipedShellCommand : public CShellProcess {
private :
	char **cmd;
	int pos;

public :
	CPipedShellCommand(string &comm) : CShellProcess(comm) {
	};
	CPipedShellCommand(char **argv, int p) : CShellProcess() { 
		cmd = argv;
		pos = p;
	};
	~CPipedShellCommand() {};

	virtual int read_upstream(const char *buf) {
		cout << buf;

		return 1;
	};
	virtual int read_downstream(const char *buf) {
	};
	virtual int read_errstream(const char *buf) {
		cerr << buf;

		return 1;
	};
	
	virtual void before_run() {
		if(command=="sort") {
for(long i=0;i<10000;i++) {
			write_downstream("woorung nara\n");
			write_downstream("hahahahaha\n");
			write_downstream("babo woorung\n");
}
		}
	};

    virtual void run() {
	int pos;
	string line;
	char each_cmd[100];

	FILE *p[2];

	sprintf(each_cmd, "%s > /tmp/has_woorung.txt", (char *)command.c_str());
	cerr << "saved to /tmp/has_woorung.txt" << endl;
	p[0]  = popen(each_cmd, "w");
	if(!p[0]) {
	    cerr << "### pipe open error : " << command << endl;
	}

	sprintf(each_cmd, "%s > /tmp/has_no_woorung.txt", (char *)command.c_str());
	cerr << "saved to /tmp/has_no_woorung.txt" << endl;
	p[1]  = popen(each_cmd, "w");
	if(!p[1]) {
	    cerr << "### pipe open error : " << command << endl;
	}

	while(!cin.eof()) {
	    getline(cin, line);
	    pos = line.find("woorung");
	    if(pos>=0&&pos<line.length()) fprintf(p[0], "%s\n", (char *)line.c_str());
	    else fprintf(p[1], "%s\n", (char *)line.c_str());
	}

	pclose(p[0]);
	pclose(p[1]);
    };
};

int main(int argc,char *argv[])
{
    vector<CPipedShellCommand *> pv;
    string command = "sort";

    int opt;
    static char optstr[] = "e";
    int cmd_pos = -1;

    while((opt=getopt(argc,argv,optstr))!=-1) {
	switch(opt) {
	    case 'e' :
		cmd_pos = optind;
		break;
	    default :
		break;
	}
    }

    if(cmd_pos<0) {
	CPipedShellCommand *psh = new CPipedShellCommand(command);
	pv.push_back(psh);
    }
    else {
	cout << "no no no no" << endl;
    }

    pv[0]->start();

    pv[0]->waits();

    cout << "status after exectuion = " << pv[0]->get_status() << endl;

    delete pv[0];
}
